package cn.uncode.dal.router.strategy;

import java.util.Map;

import cn.uncode.dal.utils.IDGenerateUtils;

public class DefaultShardingStrategy implements ShardingStrategy {
	
	
	/**
	 * 所有分片表名称
	 */
	private static final String[] SHARDING_TABLE_NAMES = new String[]{
			"orders1", 
			"orders2", 
			"orders3", 
			"orders4", 
			"orders5", 
	};
	/**
	 * 取余10后对应不同分片
	 * 不同分片的id后缀
	 */
	private static final int[] SHARDING_ID_SUFFIX = new int[]{
			100, 101, 102, 103, 104, 105, 106, 107, 108, 109
	};
	

	@Override
	public String[] selectAllShard(String tablbName) {
		return SHARDING_TABLE_NAMES;
	}

	@Override
	public long createShardId(String field, Map<String, Object> obj) {
		Object id = obj.get(field);
		if(id != null){
			long val = Long.valueOf(id + "");
			int mod = (int) (val%10);
			return IDGenerateUtils.getId(SHARDING_ID_SUFFIX[mod]);
		}
		return IDGenerateUtils.getId(SHARDING_ID_SUFFIX[0]);
	}

	/**
	 * id分片和分片表的对应关系
	 *
	 */
	@Override
	public String selectShardFromId(String tablbName, long id) {
		int shardingNo = (int) (id % 1000);
		String table = null;
		switch (shardingNo) {
		case 100:
		case 101:
			table = "orders1";
			break;
		case 102:
		case 103:
			table = "orders2";
			break;
		case 104:
		case 105:
			table = "orders3";
			break;
		case 106:
		case 107:
			table = "orders4";
			break;
		case 108:
		case 109:
			table = "orders5";
			break;

		default:
			table = "orders1";
			break;
		}
		return table;
	}

	@Override
	public String selectShardFromField(String tablbName, Object obj) {
		return null;
	}

}
